# -*- coding: utf-8 -*-
"""
日志级别：CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

默认情况下日志信息输出到控制台，默认情况下输出警告级别以上日志


默认日志格式：日志级别:日志实例:日志消息

占位符%s


"""
import os

import logging
import time
from logging import config
from queue import Queue

from py_python.py_logger.log_handler import test_logger_handler, thread_local_name

logger = logging.getLogger(__name__)

# log_directory = os.path.join(py_global.project_path, '../logs')
log_directory = '../../logs'
if not os.path.exists(log_directory):
    os.makedirs(log_directory)
    pass

extra_filed = f'{thread_local_name}:%({thread_local_name})s'
custom_format = f'%(asctime)s %(levelname)8s {extra_filed} %(filename)s(%(lineno)s) (%(funcName)s):%(message)s'
logger_format = '%(asctime)s %(levelname)8s %(funcName)16s %(filename)16s:%(lineno)3d %(message)s'
thread_format = '%(asctime)s %(process)5d %(processName)16s %(filename)16s:%(lineno)3d %(message)s'
process_format = '%(asctime)s %(thread)5d %(threadName)16s %(filename)16s:%(lineno)3d %(message)s'

log_file_max_bytes = 10 * 1024 * 1024
log_file_backup_count = 100


def test_basic_config():
    """基础配置"""
    # stream和filename同时使用，filename生效，stream无效
    logging.basicConfig(filename=os.path.join(log_directory, 'logging.log'),
                        format=logger_format,
                        datefmt='%H:%M:%S',
                        level=logging.DEBUG)
    # 调试日志
    logging.debug('init_logging success')
    pass


DICT_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': custom_format,
            'style': '%',
        },
    },
    'filters': {
        'custom_filter': {
            '()': 'py_language.py_logger.log_handler.CustomFilter'
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(log_directory, f'log-{time.strftime("%Y-%m-%d")}.log'),
            'mode': 'a+',
            'maxBytes': log_file_max_bytes,
            'backupCount': log_file_backup_count,
            'encoding': 'utf-8',
            'formatter': 'default',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'default',
        },
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(log_directory, f'error-{time.strftime("%Y-%m-%d")}.log'),
            'mode': 'a+',
            'maxBytes': log_file_max_bytes,
            'backupCount': log_file_backup_count,
            'encoding': 'utf-8',
            'formatter': 'default',
        },
        'queue_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.QueueHandler',
            'queue': Queue(),
        },
        'custom_handler': {
            'level': 'DEBUG',
            'class': 'py_language.py_logger.log_handler.CustomHandler',
            'filters': [
                'custom_filter',
            ]
        },
    },
    'loggers': {
        'default': {
            'handlers': ['default', ],
            'level': 'INFO',
            'propagate': False,
        },
        'console': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
    'root': {
        'handlers': ['custom_handler', 'queue_handler', 'default', 'error', 'console', ],
        'level': 'INFO',
    },
}


def test_dict_config():
    config.dictConfig(DICT_CONFIG)
    pass


def test_logger_config():
    logger.info('info')
    logger.error('error')
    logger.exception('exception')
    logger.debug('debug')

    logger.warning('msg:%s', 'message')


if __name__ == '__main__':
    # warning console 控制台默认输出警告级别以上日志
    # logging.warning('warning')

    # test_basic_config()
    test_dict_config()
    # test_logger_config()
    test_logger_handler()
    pass
